import router from './router'
import store from './store'
import { getToken } from '@/utils/auth'

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist
router.beforeEach(async (to, from, next) => {
  const token = getToken()
  if (whiteList.indexOf(to.path) !== -1) {
    // in the free login whitelist, go directly
    next()
  }
  else if (token) {
    const hasMenus = store.getters.menus
    const allButtomMenus = store.getters.allButtomMenus
    // const hasDicts = store.getters.dicts && store.getters.dicts.length > 0
    // if(!hasDicts){
    //   await store.dispatch('dict/initDicts')
    // }
    if (!hasMenus) {
      await store.dispatch('permission/getSelfMenus').then(() => {
        const hasRouters = store.getters.routers
        if (hasRouters) {
          router.addRoutes(store.getters.routers)
        }
      })
      if (allButtomMenus) {
        await store.dispatch('permission/getAllButtomMenus')
      }
      if (from.name === 'Login') {
        next()
      } else {
        next({ ...to, replace: true })
      }
    } else {
      next()
    }
  } else {
    next(`/login`) // 否则全部重定向到登录页
  }
})